package net.beyondts.mplug.listener;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * Project: mplug-project<br/>
 * Description: This is a listener which listens the Spring's ApplicationPreparedEvent, this event occurs before Spring Context refreshing.<br/>
 *              In the listener, the base package of MPLUG classes and some other base packages defined in spring application properties (name:basePackagesToScan) will all be added to scan.
 * Created at: 2019-1-14<br/>
 * Owned by beyondts.
 *
 * @author blazecrystal
 * @version 1.0.0
 */
public class SpringAutoScanListener implements ApplicationListener<ApplicationPreparedEvent> {
    private static Logger LOGGER = LoggerFactory.getLogger(SpringAutoScanListener.class);
    private static final String MPLUG_SCAN_PACKAGE = "net.beyondts.mplug";

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event) {
        ApplicationContext ac = event.getApplicationContext();
        List<String> basePackages = new ArrayList<>();
        String tmpValue = ac.getEnvironment().getProperty("bascPackagesToScan");
        if (StringUtils.isNotBlank(tmpValue)) {
            String[] tmpArray = tmpValue.split(",");
            for (String tmp : tmpArray) {
                if (StringUtils.isNotBlank(tmp)) {
                    basePackages.add(tmp.trim());
                }
            }
        }
        basePackages.add(MPLUG_SCAN_PACKAGE);
        if (event.getApplicationContext() instanceof AnnotationConfigServletWebServerApplicationContext) {
            ((AnnotationConfigServletWebServerApplicationContext) ac).scan(basePackages.toArray(new String[0]));
        } else if (event.getApplicationContext() instanceof AnnotationConfigApplicationContext) {
            ((AnnotationConfigApplicationContext) ac).scan(basePackages.toArray(new String[0]));
        }
        LOGGER.debug(basePackages.size() + " base packages scanned : " + StringUtils.join(basePackages, ", "));
    }
}
